﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JBeamLibrary.Tools;
using JBeamLibrary.VehicleParts.Collections;
using JBeamLibrary.VehicleParts.Elements;
using JBeamLibrary.VehicleParts.Interfaces;

namespace JBeamLibrary.VehicleParts.Groups
{
    public class Ties : IVehicleGroup<Tie>
    {
        #region Fields

        private readonly TieCollection _collection = new TieCollection();

        #endregion

        #region Indexers

        /// <summary>Gets the tie at the specified index</summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public Tie this[int index]
        {
            get
            {
                if (Collection.Count == 0)
                    return null;
                if (index < 0 || index >= Collection.Count)
                    return null;
                return Collection[index];
            }
        }

        /// <summary>Gets the beam with the specified node ID</summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        public Tie this[string nodeId]
        {
            get { return Collection.FirstOrDefault(tie => tie.NodeId.Equals(nodeId)); }
        }

        #endregion

        #region Properties

        public TieCollection Collection
        {
            get { return _collection; }
        }

        public IVehicleGroupCollection<Tie> GroupCollection
        {
            get { return Collection; }
        }

        public int Count
        {
            get { return Collection.Count; }
        }

        public bool IsEmpty
        {
            get
            {
                return GroupHelper.GetPropertyLists(this).All(list => list.Count == 0) && Collection.Count == 0;
            }
        }

        #endregion

        #region Methods

        public void SetElementValue(int index, string propName, object value)
        {
            var elem = Collection[index];
            var prop = elem.GetType().GetProperty(propName);
            prop.SetValue(elem, value);
        }

        public object GetElementValue(int index, string propName)
        {
            var elem = Collection[index];
            var prop = elem.GetType().GetProperty(propName);
            return prop.GetValue(elem);
        }

        public IEnumerable<KeyValuePair<string, object>> GetElementValues(int index)
        {
            var elem = Collection[index];
            var props = elem.GetType().GetProperties();
            return props.Select(prop => new KeyValuePair<string, object>(prop.Name, prop.GetValue(elem))).AsEnumerable();
        }

        #endregion
    }
}
